<?php
/**
 * @desc   Created by PhpStorm.
 * @author laowng
 * @since  2018/8/16 10:56
 */

namespace app\admin\service;


use app\admin\common\UserFunction;
use app\admin\repository\AdminUserRepository;
use think\Exception;
use think\exception\HttpException;

class LoginService
{
    protected $user_model;
    protected $userFunction;


    public function __construct(AdminUserRepository $adminUser, UserFunction $userFunction)
    {
        $this->user_model = $adminUser;
        $this->userFunction = $userFunction;
    }

    /**
     * @param $where
     * @return array|null|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function loginName($where)
    {
        return $this->user_model->getOneInfo($where);
    }

    /**
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws Exception
     */
    public function loginUser($user_info,$data){
        //密码是否存在
        $new_pwd = true;
        $password = $data['password'];
        if(empty($user_info['salt'])){//如果salt为空，
            $password = userPassword(trim($password));
            $new_pwd = false;
        }else{
            $password = userPasswordNew(trim($password), $user_info['salt']);
        }

        if ($password !== $user_info['password']) {//验证数据库中的密码与加密之后的登录密码是否相等
                $this->userFunction->addLoginLog(2, $user_info['id'], 1);
//                $this->checkNumber();
//                $this->addErrorTime($userinfo['id']);
            throw new Exception("密码错误", 1);
        }

        //登录成功后将登录记录表中的该账户删除，并更新users表中的数据
        //$data = ['lockStatus' => '0', 'lockType' => null, 'lockEndTime' => null, 'errorTimes' => 0, 'errorTime' => null, 'loginTimes' => $userinfo['logintimes'] + 1, 'lastLoginTime' => date('Y-m-d H:i:s', time()), 'lastLoginIP' => get_client_ip()];
        if(!$new_pwd){
            $data['salt'] = randString(16);
            $data['password'] = userPasswordNew(trim($password), $data['salt']);
        }
        // 修改表数据
        unset($data['name']);
        $save_data = $this->user_model->userSave($data['password'],$data);
        //将用户信息保存到session中
        setSession($user_info);
        $this->userFunction->addLoginLog(2, $user_info['id'], 1,1);
        // 记住用户名
        /*$saveNull = I('post.saveNull');//将简单的用户信息，写入cookie中
        if ($saveNull==1) {
            cookie('saveNull', $userinfo["mobile"], 3600 * 24 * 7);

        } else {
            cookie('saveNull', null);

        }*/
        return $save_data;
    }

}